package com.tiantianyuegou.activity;

import android.app.Dialog;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.LoginFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.tiantianyuegou.activity.BaseActivity;
import com.tiantianyuegou.R;
import com.tiantianyuegou.adapter.TaxAdapter;
import com.tiantianyuegou.constant.Constant;
import com.tiantianyuegou.http.ApiDefine;
import com.tiantianyuegou.http.SPHelper;
import com.tiantianyuegou.model.ProductSettingModel;
import com.tiantianyuegou.model.TaxModel;
import com.tiantianyuegou.util.LoadingDialog;
import com.tiantianyuegou.util.MultipartEntity;
import com.tiantianyuegou.util.PictureUtil;
import com.tiantianyuegou.util.Tools;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


/**
 * 商品发布界面
 * Created by ivany on 2016/1/19.
 */
public class PublicProductActivity extends BaseActivity implements TextWatcher, View.OnClickListener {

    private LinearLayout mLinear_take_photo, mLinear_dot;
    private ImageButton mBtn_take_photo, mBtn_take_photo_small;
    private ViewPager mPager_photos;
    private EditText mEt_title, mEt_price;
    private TextView mTxt_title_count, mTxt_add, mTxt_public, mTxt_type, mTxt_class, mTxt_tax, mTxt_size,
            mTxt_program, mTxt_desp, mTxt_brand;
    private RelativeLayout mRelate_type, mRelate_class, mRelate_tax, mRelate_size,
            mRelate_program, mRelate_desp, mRelate_brand;


    private Dialog dialog, mTaxDialog;
    private List<Bitmap> mPhotos;//图片集合
    private Bitmap mBitmap;
    private Handler mHandler = new Handler();

    private int mPosition;//记录点击的图片位置
    private MyPageChangeListener mListener = new MyPageChangeListener();
    private MyViewPager mAdapter;

    private List<String> mPhotoUrl = new ArrayList<>();//存放图片url的list
    private ArrayList<String> mDespPicUrl = new ArrayList<>();//存放商品描述的图片的url
    private String mDesp;//商品的描述

    private String mCategoryID;//商品类型的id
    private String mBrandId;//商品的品牌id
    private ArrayList<ProductSettingModel> mProgramList;//选择的商品的栏目
    private String mProductSize;//商品规格数据

    private List<TaxModel> mTaxData;//纳税比例数组
    private String mTax;//选择的纳税费
    private TaxAdapter mTaxAdapter;

  LoadingDialog mLoadingDialog;


    Runnable circleImage = new Runnable() {
        @Override
        public void run() {
            if (mPager_photos.getCurrentItem() == (mPhotos.size() - 1)) {
                mPager_photos.setCurrentItem(0, false);
            } else {
                mPager_photos.setCurrentItem(mPager_photos.getCurrentItem() + 1, true);
            }
            updateDot();
            mHandler.postDelayed(circleImage, 3000);
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish_product);
     Tools.changeSystemBar(this);
        setTitle("发布商品");
        initViews();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacks(circleImage);
    }

    @Override
    public void findViewByIds() {
        mBtn_take_photo = (ImageButton) findViewById(R.id.public_product_take_photo);
        mBtn_take_photo_small = (ImageButton) findViewById(R.id.public_product_take_photo_small);
        mBtn_take_photo_small.setVisibility(View.GONE);
        mPager_photos = (ViewPager) findViewById(R.id.public_product_photos);
        mLinear_dot = (LinearLayout) findViewById(R.id.public_product_dot);
        mEt_title = (EditText) findViewById(R.id.public_product_title);
        mTxt_title_count = (TextView) findViewById(R.id.public_product_title_count);
        mRelate_type = (RelativeLayout) findViewById(R.id.public_product_type_relate);
        mRelate_class = (RelativeLayout) findViewById(R.id.public_product_class_relate);
        mRelate_tax = (RelativeLayout) findViewById(R.id.public_product_tax_relate);
        mEt_price = (EditText) findViewById(R.id.public_product_price);
        mRelate_brand = (RelativeLayout) findViewById(R.id.public_product_brand);
        mRelate_size = (RelativeLayout) findViewById(R.id.public_product_size);
        mRelate_program = (RelativeLayout) findViewById(R.id.public_product_programa);
        mRelate_desp = (RelativeLayout) findViewById(R.id.public_product_desp);
        mTxt_add = (TextView) findViewById(R.id.public_product_add);
        mTxt_public = (TextView) findViewById(R.id.public_product_now);
        mTxt_type = (TextView) findViewById(R.id.public_product_type_txt);
        mTxt_class = (TextView) findViewById(R.id.public_product_class_txt);
        mTxt_tax = (TextView) findViewById(R.id.public_product_tax);
        mTxt_size = (TextView) findViewById(R.id.public_product_size_txt);
        mTxt_program = (TextView) findViewById(R.id.public_product_programa_txt);
        mTxt_desp = (TextView) findViewById(R.id.public_product_desp_txt);
        mTxt_brand = (TextView) findViewById(R.id.public_product_brand_txt);
    }

    @Override
    public void initListener() {
        mBtn_take_photo.setOnClickListener(this);
        mBtn_take_photo_small.setOnClickListener(this);
        mEt_title.addTextChangedListener(this);
        mEt_price.addTextChangedListener(this);
        mRelate_type.setOnClickListener(this);
        mRelate_class.setOnClickListener(this);
        mRelate_tax.setOnClickListener(this);
        mRelate_size.setOnClickListener(this);
        mRelate_program.setOnClickListener(this);
        mRelate_desp.setOnClickListener(this);
        mRelate_brand.setOnClickListener(this);
        mTxt_add.setOnClickListener(this);
        mTxt_public.setOnClickListener(this);
        mPager_photos.setOnPageChangeListener(mListener);
    }

    @Override
    public void initData() {
        mPhotos = new ArrayList<>();
        mAdapter = new MyViewPager();
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        String title = mEt_title.getText().toString();
        if (title != null && !"".equals(title)) {
            mTxt_title_count.setText(title.length() + "/40");
        } else {
            mTxt_title_count.setText("0/40");
        }

        String price = mEt_price.getText().toString();
        if (price.contains(".")) {
            if (price.substring(price.indexOf(".") + 1).length() > 2) {
                mEt_price.setText(price.substring(0, price.length() - 1));
                mEt_price.setSelection(mEt_price.getText().toString().length());
                Toast.makeText(this, "售价只能包含两位小数", Toast.LENGTH_SHORT).show();
            }
            if (price.substring(0, price.indexOf(".")).length() > 6) {
                StringBuffer priceStr = new StringBuffer();
                priceStr.append(price.substring(0, 6)).append(price.substring(price.indexOf(".")));
                mEt_price.setText(priceStr.toString());
                mEt_price.setSelection(mEt_price.getText().toString().length());
                Toast.makeText(this, "售价不能超过六位数(不包含小数)", Toast.LENGTH_SHORT).show();
            }
        } else {
            if (price.length() > 6) {
                mEt_price.setText(price.substring(0, 6));
                mEt_price.setSelection(mEt_price.getText().toString().length());
                Toast.makeText(this, "售价不能超过六位数(不包含小数)", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.public_product_take_photo_small:
            case R.id.public_product_take_photo:
                if (mPhotoUrl.size() >= 5) {
                    showMsg("只能上传5张图片,请删除图片后再上传");
                } else {
                    headDialog();
                }
                break;
            case R.id.public_product_type_relate:
                Intent intent = new Intent(this, ProductTypeActivity.class);
                startActivityForResult(intent, Constant.SELECT_TYPE_REQUEST);
                break;
            case R.id.public_product_class_relate:
                Intent intent1 = new Intent(this, ProductClassOneActivity.class);
                startActivityForResult(intent1, Constant.GET_PRODUCT_CLASS_ONE_REQUEST);
                break;
            case R.id.public_product_tax_relate:
                taxDialog();
                break;
            case R.id.public_product_size:
                if (mCategoryID == null || "".equals(mCategoryID)) {
                    Toast.makeText(this, "请先选择商品的类型", Toast.LENGTH_SHORT).show();
                } else {
                    Intent intent4 = new Intent(PublicProductActivity.this, ProductSizeActivity.class);
                    intent4.putExtra("id", mCategoryID);
                    startActivityForResult(intent4, Constant.SELECT_SIZE_REQUEST);
                }
                break;
            case R.id.public_product_programa:
                Intent intent2 = new Intent(this, ProductProgramaActivity.class);
                if (mProgramList != null && mProgramList.size() > 0) {//当用户已经进行勾选过的时候
                    intent2.putExtra("alreadySelect", mProgramList);
                }
                startActivityForResult(intent2, Constant.SELECT_PROGRAM_REQUEST);
                break;
            case R.id.public_product_desp:
                Intent intent3 = new Intent(this, ProductDespActivity.class);
                if (mDesp != null && !"".equals(mDesp)) {
                    intent3.putExtra("desp", mDesp);
                }
                if (mDespPicUrl != null && mDespPicUrl.size() > 0) {
                    intent3.putExtra("picUrl", mDespPicUrl);
                }
                startActivityForResult(intent3, Constant.EDIT_DESP_REQUEST);
                break;
            case R.id.public_product_brand:
                if (mCategoryID == null || "".equals(mCategoryID)) {
                    Toast.makeText(this, "请先选择商品的类型", Toast.LENGTH_SHORT).show();
                } else {
                    Intent intent5 = new Intent(this, ProductBrandActivity.class);
                    intent5.putExtra("id", mCategoryID);
                    startActivityForResult(intent5, Constant.GET_PRODUCT_BRAND_REQUEST);
                }

                break;
            case R.id.public_product_add:

                if (verify()) {
                    mLoadingDialog = new LoadingDialog(this);
                    mLoadingDialog.setMsg("正在加入仓库");
                    mLoadingDialog.show();
                    publicOrSave("2");
                }
                break;
            case R.id.public_product_now:

                if (verify()) {
                    mLoadingDialog = new LoadingDialog(this);
                    mLoadingDialog.setMsg("正在发布商品");
                    mLoadingDialog.show();
                    publicOrSave("1");
                }
                break;
        }
    }

    //进行校验
    private boolean verify() {
        String price = mEt_price.getText().toString();
        String name = mEt_title.getText().toString();
        String textClass = mTxt_class.getText().toString();
        String tax = mTxt_tax.getText().toString();
        if (mPhotoUrl == null || mPhotoUrl.size() == 0) {
            Toast.makeText(this, "请上传商品图片", Toast.LENGTH_SHORT).show();
            return false;
        } else if (name == null || "".equals(name)) {
            Toast.makeText(this, "请输入商品描述", Toast.LENGTH_SHORT).show();
            return false;
        } else if (mCategoryID == null || "".equals(mCategoryID)) {
            Toast.makeText(this, "请选择商品类型", Toast.LENGTH_SHORT).show();
            return false;
        } else if (textClass == null || "".equals(textClass)) {
            Toast.makeText(this, "请选择商品分类", Toast.LENGTH_SHORT).show();
            return false;
        } else if (tax == null || "".equals(tax)) {
            Toast.makeText(this, "请选择服务费纳税比例", Toast.LENGTH_SHORT).show();
            return false;
        } else if (mBrandId == null || "".equals(mBrandId)) {
            Toast.makeText(this, "请选择商品品牌", Toast.LENGTH_SHORT).show();
            return false;
        } else if (mProductSize == null || "".equals(mProductSize)) {
            Toast.makeText(this, "请选择商品规格", Toast.LENGTH_SHORT).show();
            return false;
        }
//        else if (mProgramList == null || mProgramList.size() == 0) {
//            Toast.makeText(this, "请设置商品栏目", Toast.LENGTH_SHORT).show();
//            return false;
//        } else if ((mDesp == null || "".equals(mDesp)) && (mDespPicUrl == null || mDespPicUrl.size() == 0)) {
//            Toast.makeText(this, "请设置商品的描述", Toast.LENGTH_SHORT).show();
//            return false;
//        }
        else if (price.contains(".")) {
            if ((price.substring(price.indexOf(".") + 1).length() > 2)) {
                Toast.makeText(this, "售价只能包含两位小数", Toast.LENGTH_SHORT).show();
                return false;
            } else {
                return true;
            }
        } else {
            return true;
        }
    }

    //调用发布商品的接口
    private void publicOrSave(final String type) {
        RequestParams params = new RequestParams();
        params.addBodyParameter("tsId", SPHelper.getTSId());
        params.addQueryStringParameter("tpName", mEt_title.getText().toString());
        params.addBodyParameter("categoryId", mCategoryID);
        params.addBodyParameter("cpId", Constant.productClassThreeId + "");
        params.addBodyParameter("brandId", mBrandId);

        StringBuffer desp = new StringBuffer();
        desp.append(mDesp + "").append(",");
        if (mDespPicUrl != null) {
            for (int i = 0; i < mDespPicUrl.size(); i++) {
                desp.append(mDespPicUrl.get(i)).append(",");
            }
        }
        if (desp.length() > 1) {
            params.addQueryStringParameter("desp", desp.substring(0, desp.length() - 1));
        } else {
            params.addQueryStringParameter("desp", "");
        }
        params.addBodyParameter("spRatio", mTax);
        StringBuffer column = new StringBuffer();
        if (mProgramList != null) {
            for (int i = 0; i < mProgramList.size(); i++) {
                column.append(mProgramList.get(i).getId()).append(",");
            }
        }
        if (column.length() > 0) {
            params.addBodyParameter("column", column.substring(0, column.length() - 1));
        } else {
            params.addBodyParameter("column", "");
        }
        params.addBodyParameter("salePrice", mEt_price.getText().toString());
        params.addQueryStringParameter("specJson", mProductSize);
        StringBuffer photo = new StringBuffer();
        for (int i = 0; i < mPhotoUrl.size(); i++) {
            photo.append(mPhotoUrl.get(i)).append(",");
        }
        params.addBodyParameter("photo", photo.substring(0, photo.length() - 1));
        params.addBodyParameter("type", type);
//        Log.e("TAG", "public product request params: tsId:" + SPHelper.getTSId() + ":tpName:" + mEt_title.getText().toString()
//                + ":categoryId:" + mCategoryID + ":cpId:" + Constant.productClassThreeId
//                + ":brandId:" + mBrandId + ":desp:" + desp.substring(0, desp.length() - 1) + ":spRatio:" + mTax
//                + ":column:" + column.substring(0, column.length() - 1) + ":salePrice:" + mEt_price.getText().toString()
//                + ":specJson:" + mProductSize + ":photo:" + photo.substring(0, photo.length() - 1) + ":type:" + type);
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.GOODS_RELEASE, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                mLoadingDialog.dismiss();
                Log.e("TAG", "public product response:" + responseInfo.result);
                if (TextUtils.isEmpty(responseInfo.result)) {
                    if ("1".equals(type)) {
                        showMsg("发布商品失败");
                    } else {
                        showMsg("加入仓库失败");
                    }
                } else {
                    try {
                        JSONObject root = new JSONObject(responseInfo.result);
                        String code = root.getString("code");
                        if ("100".equals(code)) {
                            Intent intent = new Intent(PublicProductActivity.this, GoodsManageActivity.class);
                            if ("1".equals(type)) {
                                intent.putExtra("type", "1");
                                showMsg("发布商品成功");
                            } else {
                                intent.putExtra("type", "2");
                                showMsg("加入仓库成功");
                            }
                            startActivity(intent);
                            finish();
                        } else {
                            String msg = root.getString("message");
                            showMsg(msg);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        showMsg("操作失败");
                    }
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                mLoadingDialog.dismiss();
                Log.e("TAG", "public product failure:" + s);
                showMsg("当前网络不可用,请检查您的网络设置");
            }
        });


    }


    /**
     * 加载轮播图
     */
    public void initCircle() {
        mBtn_take_photo_small.setVisibility(View.VISIBLE);
        initDots();
        // 通过适配器引入图片
        mPager_photos.setAdapter(mAdapter);
        int centerValue = mPhotos.size() / 2;
        int value = centerValue % mPhotos.size();
        mPager_photos.setCurrentItem(centerValue - value);
        // 更新
        updateDot();
        //mHandler.sendEmptyMessageDelayed(0, 3000);
        mHandler.removeCallbacks(circleImage);
        mHandler.post(circleImage);
        Log.e("PublicProductActivity", "currentItem is " + mPager_photos.getCurrentItem());
    }

    private void initDots() {
        mLinear_dot.removeAllViews();
        for (int i = 0; i < mPhotos.size(); i++) {
            View view = new View(this);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(20, 20);
            if (i != 0) {
                params.leftMargin = 5;
            }
            view.setLayoutParams(params);
            view.setBackgroundResource(R.drawable.selecter_dot);
            mLinear_dot.addView(view);
        }
    }

    class MyViewPager extends PagerAdapter {
        @Override
        public int getCount() {
            return mPhotos.size();
        }

        /**
         * true表示无需创建 false表示需要创建
         */
        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        /**
         * 设置view多个界面
         */
        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            final Bitmap bitmap = mPhotos.get(position % mPhotos.size());
            final String url = mPhotoUrl.get(position % mPhotoUrl.size());
            View view = View.inflate(PublicProductActivity.this, R.layout.adapter, null);
            ImageView image = (ImageView) view.findViewById(R.id.image);
            image.setImageBitmap(bitmap);
            image.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(PublicProductActivity.this, CheckPhotoActivity.class);
                    intent.putExtra("pic", url);
                    mPosition = position;
                    startActivityForResult(intent, Constant.CHECK_PHOTO_REQUEST);
                }
            });
            container.addView(view);
            return view;
        }

        /**
         * 销毁page position:当前要销毁第几个page object：当前需要销毁的page
         */
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            // super.destroyItem(container, position, object);
            container.removeView((View) object);
        }
    }

    private void updateDot() {
        int currentPage = mPager_photos.getCurrentItem() % mPhotos.size();
        // 改变dot
        for (int i = 0; i < mLinear_dot.getChildCount(); i++) {
            mLinear_dot.getChildAt(i).setEnabled(i == currentPage);
        }
    }

    class MyPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrolled(int i, float v, int i1) {

        }

        @Override
        public void onPageSelected(int position) {
            if (position == (mPhotos.size() - 1)) {
//                    mPager_photos.setCurrentItem(0,true);
//                }else if(position==0){
//                    mPager_photos.setCurrentItem(mPhotos.size()-1,true);
//                }
                updateDot();
            }
        }

        @Override
        public void onPageScrollStateChanged(int i) {

        }
    }

    private Uri imageFilePath;


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == -1) {
            Intent intent = new Intent("com.android.camera.action.CROP");
            Uri data2 = null;
            if (data == null) {
                data2 = PictureUtil.getImageUri();
            } else {
                data2 = data.getData();
            }
            if (requestCode == Constant.MEDIA_CROP_REQUEST_CODE) {
                mBitmap = decodeUriAsBitmap(imageFilePath);// decode
                uploadBmp(mBitmap); //上传图片到服务器端
                //initCircle();//初始化轮播图
            } else if (requestCode == Constant.MEDIA_IMAGE_REQUEST_CODE) {
                if (data != null) {
                    imageFilePath = data.getData();
                    cropImageUri(imageFilePath, 300, 300,
                            Constant.MEDIA_CROP_REQUEST_CODE);
                }
            } else if (requestCode == Constant.MEDIA_CAMERA_REQUEST_CODE) {
                cropImageUri(imageFilePath, 300, 300, Constant.MEDIA_CROP_REQUEST_CODE);
            } else if (requestCode == PictureUtil.PHOTO_PICKED_WITH_DATA) {
                intent.setDataAndType(data2, "image/*");
                intent.putExtra("crop", true);
                // 设置裁剪尺寸
                intent.putExtra("aspectX", 1);
                intent.putExtra("aspectY", 1);
                intent.putExtra("outputX", 300);
                intent.putExtra("outputY", 300);
                intent.putExtra("return-data", true);
                intent.putExtra(MediaStore.EXTRA_OUTPUT,
                       PictureUtil.getImageCaiUri());
                startActivityForResult(intent,PictureUtil.PHOTO_CROP);
            } else if (requestCode == PictureUtil.PHOTO_CROP) {
                Bundle bundle = data.getExtras();
                Bitmap myBitmap = (Bitmap) bundle.get("data");
                mBitmap = PictureUtil.comp(myBitmap);

                String fileName = PictureUtil.getCharacterAndNumber();
                File file = new File(PictureUtil.PHOTO_DIR, fileName + ".png");
                PictureUtil.saveMyBitmap(mBitmap, file);
                // mPhotos.add(bitImage);
                uploadBmp(mBitmap);//上传图片
                // initCircle();//初始化轮播图
            }
            dialog.dismiss();
        } else if (requestCode == Constant.CHECK_PHOTO_REQUEST) {
            if (resultCode == Constant.CHECK_PHOTO_RESULT) {
                Log.e("TAG", "remove position is :" + mPosition);
                mPhotos.remove(mPosition);
                mPhotoUrl.remove(mPosition);
                if (mPhotos.size() == 0) {
                    //将所有与轮播图相关的都取消掉
                    mPager_photos.removeOnPageChangeListener(mListener);
                    mAdapter.notifyDataSetChanged();
                    mPager_photos.removeAllViews();
                    mHandler.removeCallbacks(circleImage);
                    mBtn_take_photo.setVisibility(View.VISIBLE);
                    mBtn_take_photo_small.setVisibility(View.GONE);
                } else {
                    initCircle();
                }
            }
        } else if (requestCode == Constant.SELECT_TYPE_REQUEST) {
            if (resultCode == Constant.SELECT_TYPE_RESULT) {
                mTxt_type.setText(data.getStringExtra("label"));
                mCategoryID = data.getStringExtra("id");
            }
        } else if (requestCode == Constant.GET_PRODUCT_CLASS_ONE_REQUEST) {
            if (resultCode == Constant.GET_PRODUCT_CLASS_ONE_RESULT) {
                mTxt_class.setText(Constant.productClassOneName + " " + Constant.productClassTwoName + " " + Constant.productClassThreeName);
            }
        } else if (requestCode == Constant.SELECT_PROGRAM_REQUEST) {
            if (resultCode == Constant.SELECT_PROGRAM_RESULT) {
                mProgramList = (ArrayList<ProductSettingModel>) data.getSerializableExtra("programList");
                Log.e("TAG", "program size:" + mProgramList.size());
                if (mProgramList.size() > 0) {
                    mTxt_program.setText("已编辑");
                } else {
                    mTxt_program.setText("");
                }
            }
        } else if (requestCode == Constant.EDIT_DESP_REQUEST) {
            if (resultCode == Constant.EDIT_DESP_RESULT) {
                mDesp = data.getStringExtra("desp");
                mDespPicUrl.clear();
                mDespPicUrl.addAll((ArrayList<String>) data.getSerializableExtra("picList"));
                if ((mDesp == null || "".equals(mDesp)) && (mDespPicUrl == null || mDespPicUrl.size() == 0)) {
                    mTxt_desp.setText("");
                } else {
                    mTxt_desp.setText("已编辑");
                }
            }
        } else if (requestCode == Constant.SELECT_SIZE_REQUEST) {
            if (resultCode == Constant.SELECT_SIZE_RESULT) {
                mProductSize = data.getStringExtra("productSize");
                if (mProductSize != null && !"".equals(mProductSize)) {
                    Log.e("TAG", "public product:" + mProductSize);
                    mTxt_size.setText("已编辑");
                } else {
                    mTxt_size.setText("");
                }
            }
        } else if (requestCode == Constant.GET_PRODUCT_BRAND_REQUEST) {
            if (resultCode == Constant.GET_PRODUCT_BRAND_RESULT) {
                mBrandId = data.getIntExtra("id", 0) + "";
                mTxt_brand.setText(data.getStringExtra("label"));
            }
        }
    }

    //纳税比例的弹出框
    private void taxDialog() {
        View view = getLayoutInflater().inflate(R.layout.pop_tax_window, null);
        mTaxDialog = new Dialog(this, R.style.transprentFrameWindowStyle);
        mTaxDialog.setContentView(view, new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT));
        Window window = mTaxDialog.getWindow();
        window.setWindowAnimations(R.style.main_menu_animstyle);
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.y = getWindowManager().getDefaultDisplay().getHeight();
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        mTaxDialog.onWindowAttributesChanged(wl);
        mTaxDialog.setCanceledOnTouchOutside(true);
        final ListView mTaxList;
        mTaxList = (ListView) view.findViewById(R.id.pop_tax_list);
        mTaxData = new ArrayList<>();
        mTaxAdapter = new TaxAdapter(PublicProductActivity.this);
        mTaxList.setAdapter(mTaxAdapter);
        mTaxList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String taxLabel = mTaxData.get(position).getLabel();
                Double tax = Double.valueOf(taxLabel.substring(0, taxLabel.length() - 1));
                mTax = new DecimalFormat("0.00").format(tax / 100);
                Log.e("TAG", "Tax:" + mTax + ":tax" + tax);
                mTxt_tax.setText(taxLabel);
                mTaxDialog.dismiss();
            }
        });
        //加载数据
        getTaxList();
    }

    //获取服务税缴纳比例
    private void getTaxList() {
        final LoadingDialog loadingDialog = new LoadingDialog(this);
        loadingDialog.setMsg("正在获取数据");
        loadingDialog.show();
        RequestParams params = new RequestParams();
        params.addBodyParameter("twCode", "06");
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.COMMON_DATA, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                loadingDialog.dismiss();
                Log.e("TAG", "get tax list response:" + responseInfo.result);
                if (TextUtils.isEmpty(responseInfo.result)) {
                    showMsg("暂无服务费纳税比例数据");
                } else {
                    try {
                        JSONObject root = new JSONObject(responseInfo.result);
                        String code = root.getString("code");
                        if ("100".equals(code)) {
                            JSONArray list = root.getJSONArray("list");
                            if (list.length() > 0) {
                                mTaxData.clear();
                                for (int i = 0; i < list.length(); i++) {
                                    JSONObject value = list.getJSONObject(i);
                                    TaxModel model = new TaxModel();
                                    model.setId(value.getInt("twId"));
                                    model.setLabel(value.getString("twName"));
                                    model.setCode(value.getString("twCode"));
                                    mTaxData.add(model);
                                }
                                Collections.sort(mTaxData);
//                                TODO 需要换成真正的数据名称
//                                mTaxAdapter.setData(mTaxData);
                                mTaxAdapter.notifyDataSetChanged();
                                mTaxDialog.show();
                            } else {
                                showMsg("暂无服务费纳税比例数据");
                            }
                        } else {
                            String msg = root.getString("message");
                            showMsg(msg);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        showMsg("数据解析异常");
                    }
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                loadingDialog.dismiss();
                showMsg("当前网络不可用,请检查您的网络设置");
                Log.e("TAG", "get tax list failure:" + s);
            }
        });
    }


    private void headDialog() {
        View view = getLayoutInflater().inflate(R.layout.dialog_head, null);
        dialog = new Dialog(this, R.style.transprentFrameWindowStyle);
        dialog.setContentView(view, new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT));
        Window window = dialog.getWindow();
        window.setWindowAnimations(R.style.main_menu_animstyle);
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.y = getWindowManager().getDefaultDisplay().getHeight();
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        dialog.onWindowAttributesChanged(wl);
        dialog.setCanceledOnTouchOutside(true);

        Button dialog_photograph, dialog_photo, dialog_quit;

        dialog_photograph = (Button) view.findViewById(R.id.dialog_photograph);
        dialog_photo = (Button) view.findViewById(R.id.dialog_photo);
        dialog_quit = (Button) view.findViewById(R.id.dialog_quit);

        /**
         * 系统相机
         */
        dialog_photograph.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // 调用系统相机
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                ContentValues values = new ContentValues(3);
                values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
                imageFilePath = PublicProductActivity.this.getContentResolver()
                        .insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                                values);

                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageFilePath);
                startActivityForResult(intent, Constant.MEDIA_CAMERA_REQUEST_CODE);

            }
        });

        /**
         * 系统相册
         */
        dialog_photo.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // 调用系统相册
                PictureUtil.doPickPhotoFromGallery(PublicProductActivity.this);
            }
        });

        dialog_quit.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }


    private void uploadBmp(Bitmap b) {
        new UploadTask().execute(b);
    }

    private class UploadTask extends AsyncTask<Bitmap, String, String> {
        LoadingDialog loadingDialog = new LoadingDialog(PublicProductActivity.this);

        public UploadTask() {
            loadingDialog.setMsg("正在上传图片");
            loadingDialog.show();
        }

        protected String doInBackground(Bitmap... bitmaps) {
            if (bitmaps[0] == null)
                return null;

            Bitmap bitmap = bitmaps[0];
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
            InputStream in = new ByteArrayInputStream(stream.toByteArray());

            DefaultHttpClient httpclient = new DefaultHttpClient();
            ByteArrayOutputStream baos;
            try {
                HttpPost httppost = new HttpPost(ApiDefine.UPLOAD_PRODUCT_PIC); // server

                MultipartEntity reqEntity = new MultipartEntity();

                // reqEntity.addPart("tmId", SPHelper.getTmId() + "");
                reqEntity.addPart("photo", System.currentTimeMillis() + ".jpg",
                        in);

                httppost.setEntity(reqEntity);

                Log.e("requestLineInfo>>", httppost.getRequestLine() + "");
                HttpResponse response = null;
                baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[8192];
                try {
                    response = httpclient.execute(httppost);
                    if (response != null) {
                        StatusLine statusLine = response.getStatusLine();
                        Log.e("upload status", statusLine.getStatusCode() + "");
                        if (statusLine != null
                                && statusLine.getStatusCode() == HttpStatus.SC_OK) {
                            InputStream is = response.getEntity().getContent();
                            baos.reset();
                            for (int len = is.read(buffer); len != -1; len = is
                                    .read(buffer)) {
                                baos.write(buffer, 0, len);
                            }
                            Log.e("baos :", baos.toString());
                        }
                    }
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (response != null) {
                    Log.e("upload photo response>>", response.getStatusLine().toString());
                }
            } finally {

            }

            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            return baos.toString();
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            loadingDialog.dismiss();
            uploadAvaterResult(result);
        }
    }

    /**
     * 解析是否上传头像成功
     */
    private void uploadAvaterResult(String resultJson) {
        try {
            JSONObject root = new JSONObject(resultJson);
            String code = root.getString("code");
            if ("100".equals(code)) {
                mPhotoUrl.add(root.getString("result"));
                mPhotos.add(mBitmap);
                initCircle();
            } else {
                showMsg("添加图片失败");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * bitmap 转换成字节
     */
    public byte[] Bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

    /**
     * Uri转化成Bmp
     */
    private Bitmap decodeUriAsBitmap(Uri uri) {
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(getContentResolver()
                    .openInputStream(uri));
        } catch (Throwable e) {
            e.printStackTrace();
            return null;
        }
        return bitmap;
    }

    /**
     * 裁剪图片
     */
    private void cropImageUri(Uri uri, int outputX, int outputY, int requestCode) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", outputX);
        intent.putExtra("outputY", outputY);
        intent.putExtra("scale", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
        startActivityForResult(intent, requestCode);
    }


}
